package com.shauvik.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class BurstCountdown extends IOCountdown {
	List<Grid> ref = new ArrayList<Grid>();
	List<Image> imList = new ArrayList<Image>();
	private Timer animationTimer;
	Animation animation;
	public class CustomAnimation extends Animation {

		@Override
		protected void onUpdate(double progress) {
			for(Image im : imList){
				int h = im.getHeight();
				int w = im.getWidth();
				if(h<20){
					im.setHeight(h+"1px");
					im.setWidth(w+"1px");
				}else{
					im.removeFromParent();
				}
			}
		}
	}
	
	@Override
	public void initAnimation(){
		animation = new CustomAnimation();
		animationTimer = new Timer() {
			public void run() {
				runAnimation();
			}
		};
		animationTimer.scheduleRepeating(50);
	}
	
	public void runAnimation(){
		animation.run(2000);
	}
	
	public Widget buildSeparator(){
		VerticalPanel vPanel = new VerticalPanel();
		vPanel.setSpacing(5);
		for(int i=0;i<2;i++){
			Image sep = new Image("/img/sep.png");
			vPanel.add(sep);
		}
		return vPanel;
	}
	
	public Widget buildNumber(int id, String style){
		
		Grid grid = new Grid(7, 4);
	    int numRows = grid.getRowCount();
	    int numColumns = grid.getColumnCount();
	    for (int row = 0; row < numRows; row++) {
	      for (int col = 0; col < numColumns; col++) {
	        grid.setWidget(row, col, new Image("/img/gray.png"));
	      }
	    }
	    grid.ensureDebugId(style);
	    grid.setStyleName(style);
		ref.add(grid);
		return grid;
	}

	@Override
	public void animate(int[] old_digits, int[] digits) {
		for(int i=8;i>=0;i--){
			if(digits[i] == old_digits[i]){
				return;
			}
			Grid grid = ref.get(i);
			String style = grid.getStyleName();
			int[][] dig = Constants.num[digits[i]];
			for(int a=0;a<dig.length;a++){
				for(int b=0; b<dig[a].length;b++){
					//GWT.log(a+","+b);
					Widget w = grid.getWidget(a, b);
					if(w instanceof Image){
						if(dig[a][b]==1){
							((Image)w).setUrl("/img/"+style+".png"); //Can't use reflection for this
						}else{
							((Image)w).setUrl("/img/gray.png");
						}
					}
				}
			}
			int[][] hotspots = Constants.drop[digits[i]];

			for(int p=0;p<hotspots.length;p++){
					//GWT.log(hotspots[p][0]+","+hotspots[p][1]);
					Widget w = grid.getWidget(hotspots[p][0], hotspots[p][1]);
					int top = w.getAbsoluteTop();
					int left = w.getAbsoluteLeft();
					Image m = new Image("/img/"+style+".png");
					m.setStyleName("plain");
					aPanel.add(m, left, top-aPanel.getAbsoluteTop());
					imList.add(m);
			}
		}
	}
	
}
